#!/bin/bash
# - clone_url
# - pull_number
# - checkout
# - checks
# - header_filter

mkdir -p $TMP/checked_project
git clone $clone_url $TMP/checked_project
cd $TMP/checked_project
git fetch origin pull/$pull_number/head:pr-$pull_number
git checkout pr-$pull_number

# check any spec file in the checked project
if [ ! -f $TMP/checked_project/*.spec ]; then
    echo "No spec file found in the checked project."
    exit 1
fi

# apply patches for all spec files
mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
cp -r $TMP/checked_project/*.spec ~/rpmbuild/SPECS/

export CC=clang
export CXX=clang++

for spec in ~/rpmbuild/SPECS/*.spec
do
    cp -r $TMP/checked_project/* ~/rpmbuild/SOURCES/
    dnf builddep -y $spec
    rpmbuild -bb $spec
done

# traversal patched source-code directories 
for dir in ~/rpmbuild/BUILD/*/; do
    # cmake or make with compile database
    cd $dir
    if [ -f CMakeLists.txt ]; then
        mkdir build
        cd build
        cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
    else
        compiledb make 
    fi

    # run clang tidy
    run_clang_tidy=$(find /usr -name run-clang-tidy.py)
    TERM=dumb $run_clang_tidy \
        -header-filter="'${header_filter:-}'" \
        -checks="'${checks:-}'" | tee $RESULT_ROOT/$(basename $dir)-clang-tidy.result
done